package org.mall.modules.member.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mall.common.api.vo.Result;
import org.mall.common.aspect.annotation.AutoLog;
import org.mall.common.constant.CommonConstant;
import org.mall.common.system.query.QueryGenerator;
import org.mall.common.system.util.JwtUtil;
import org.mall.common.util.RedisUtil;
import org.mall.common.util.UUIDGenerator;
import org.mall.common.util.json.JacksonUtils;
import org.mall.common.util.oConvertUtils;
import org.mall.convert.ShopConvert;
import org.mall.modules.member.entity.Member;
import org.mall.modules.member.entity.MemberPro;
import org.mall.modules.member.entity.PromotionInformation;
import org.mall.modules.member.service.IMemberService;
import org.mall.modules.member.service.IPromotionInformationService;
import org.mall.modules.pojo.shop.ShopDTO;
import org.mall.modules.seller.entity.Seller;
import org.mall.modules.seller.service.ISellerService;
import org.mall.modules.shop.entity.Shop;
import org.mall.modules.shop.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * @Auther: LL
 * @Date: 2019/10/25 17:07
 */
@Slf4j
@Api(tags = "推广员的增删改查")
@RestController
@RequestMapping("/promoters")
public class PromotersController {
    @Autowired
    private IMemberService memberService;

    @Autowired
    private IPromotionInformationService promotionInformationService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private ISellerService sellerService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param member
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "推广员的增删改查-分页列表查询")
    @ApiOperation(value="推广员的增删改查-分页列表查询", notes="推广员的增删改查-分页列表查询")
    @GetMapping(value = "/web/list")
    public Result<IPage<Member>> queryPageList(Member member,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        Result<IPage<Member>> result = new Result<IPage<Member>>();
        QueryWrapper<Member> queryWrapper = QueryGenerator.initQueryWrapper(member, req.getParameterMap());
        //增加判断条件，只查询未删除的
        queryWrapper.eq("is_delete",0);
        queryWrapper.eq("type",1);
        queryWrapper.select(Member.class, info -> !info.getColumn().equals("password")
                && !info.getColumn().equals("create_time"));
        Page<Member> page = new Page<Member>(pageNo, pageSize);
        IPage<Member> pageList = memberService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param memberPro
     * @return
     */
    @AutoLog(value = "推广员的增删改查-添加")
    @ApiOperation(value="推广员的增删改查-添加", notes="推广员的增删改查-添加")
    @PostMapping(value = "/web/add")
    public Result<Member> add(@Valid @RequestBody MemberPro memberPro, BindingResult bindingResult) {
        Result<Member> result = new Result<Member>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
//        查询该推广员是否已经添加过
        Member member1=memberService.getOneUser(memberPro.getMobile());
        if(null!=member1){
            Member temp=new Member();
            temp.setId(member1.getId());
            temp.setIsDelete(0);
            temp.setType(1);
            memberService.updateById(temp);
            result.success("添加成功！");
        }else {
            Member member=new Member();
            BeanUtil.copyProperties(memberPro,member);
            try {
                member.setType(1);
                memberService.save(member);
                result.success("添加成功！");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.error500("操作失败");
            }
        }
        return result;
    }

    /**
     * 网页编辑
     *
     * @param memberPro
     * @return
     */
    @AutoLog(value = "推广员的增删改查-编辑")
    @ApiOperation(value="推广员的增删改查-编辑", notes="推广员的增删改查-编辑")
    @PostMapping(value = "/web/edit")
    public Result<Member> edit(@Valid @RequestBody MemberPro memberPro,BindingResult bindingResult) {
        Result<Member> result = new Result<Member>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        Member memberEntity = memberService.getById(memberPro.getId());
        if (memberEntity == null) {
            result.error500("未找到对应实体");
        } else {
                Member member=new Member();
                BeanUtil.copyProperties(memberPro,member);
                boolean ok = memberService.updateById(member);
                //TODO 返回false说明什么？
                if (ok) {
                    result.success("修改成功!");
                }
        }
        return result;
    }
    /**
     * 商城编辑推广员信息
     *
     * @param memberPro
     * @return
     */
    @AutoLog(value = "推广员的增删改查-编辑")
    @ApiOperation(value="推广员的增删改查-编辑", notes="推广员的增删改查-编辑")
    @PostMapping(value = "/app/edit")
    public Result<Member> editApp(@Valid @RequestBody MemberPro memberPro,BindingResult bindingResult) {
        Result<Member> result = new Result<Member>();
        if(bindingResult.hasErrors()){
            return result.error500(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
//       判断前天获取的id和从token获取的id是否相等（身份验证）
        if(JwtUtil.getUserInfoByToken().getUserId().equals(memberPro.getId())){
            Member memberEntity = memberService.getById(memberPro.getId());
            if (memberEntity == null) {

                result.error500("未找到对应实体");
            } else {
                Member member=new Member();
                BeanUtil.copyProperties(memberPro,member);
                boolean ok = memberService.updateById(member);
                //TODO 返回false说明什么？
                if (ok) {
                    result.success("修改成功!");
                }
            }
        }else {
            return result.error500("前台传递的id有误，不是本推广员的！");
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param memberPro
     * @return
     */
    @AutoLog(value = "推广员的增删改查-通过id删除")
    @ApiOperation(value="推广员的增删改查-通过id删除", notes="推广员的增删改查-通过id删除")
    @PostMapping(value = "/web/delete")
    public Result<?> delete(@RequestBody MemberPro memberPro) {
        if(memberPro==null){
            return Result.error("参数错误,id为空");
        }
        try {
            memberService.deleteById(memberPro.getId());
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param memberPro
     * @return
     */
    @AutoLog(value = "推广员的增删改查-批量删除")
    @ApiOperation(value="推广员的增删改查-批量删除", notes="推广员的增删改查-批量删除")
    @PostMapping(value = "/web/deleteBatch")
    public Result<Member> deleteBatch(@RequestBody MemberPro memberPro) {
        Result<Member> result = new Result<Member>();
        if(memberPro==null){
            return result.error500("参数错误,id为空");
        }
        if (memberPro.getId() == null || "".equals(memberPro.getId().trim())) {
            result.error500("参数不识别！");
        } else {
            this.memberService.deleteByIds(Arrays.asList(memberPro.getId().split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @return
     */
    @AutoLog(value = "推广员的增删改查-通过id查询")
    @ApiOperation(value="推广员的增删改查-通过id查询", notes="推广员的增删改查-通过id查询")
    @GetMapping(value = "/web/queryById")
    public Result<Member> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<Member> result = new Result<Member>();
        if(StringUtils.isBlank(id)){
            return  result.error500("参数错误,id为空");
        }
        Member member = memberService.getById(id);
        if (member == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(member);
            result.setSuccess(true);
        }
        return result;
    }
    @AutoLog(value = "推广员的增删改查-通过id查询")
    @ApiOperation(value="推广员的增删改查-通过id查询", notes="推广员的增删改查-通过id查询")
    @GetMapping(value = "/app/queryById")
    public Result<Member> queryAppById() {
        Result<Member> result = new Result<Member>();
        Member member = memberService.getById(JwtUtil.getUserInfoByToken().getUserId());
        if (member == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(member);
            result.setSuccess(true);
        }
        return result;
    }
    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<Member> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                Member member = JSON.parseObject(deString, Member.class);
                queryWrapper = QueryGenerator.initQueryWrapper(member, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<Member> pageList = memberService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "商城用户列表");
        mv.addObject(NormalExcelConstants.CLASS, Member.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商城用户列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<Member> listMembers = ExcelImportUtil.importExcel(file.getInputStream(), Member.class, params);
                memberService.saveBatch(listMembers);
                return Result.ok("文件导入成功！数据行数:" + listMembers.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * 推广员提交商铺信息
     * @param shopDTO
     * @param bindingResult
     * @param request
     * @return
     */
    @PostMapping("/app/modifyShopInfo")
    @Transactional
    public Result modifyShopInfo(@RequestBody @Validated ShopDTO shopDTO, BindingResult bindingResult, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
        }
        String userId=JwtUtil.getUserIdByToken();
        Member user=memberService.getById(userId);
        if (user.getType()!=1){
            return Result.error("当前用户不是推广员，无法进行推广");
        }
        if (!shopDTO.getVerificationCode().equals(redisUtil.get(CommonConstant.PREFIX_SELLER_CODE+shopDTO.getMobile()))){
            return Result.error("验证码错误");
        }
        Seller seller=new Seller();
        Seller sqlSeller =sellerService.getOneByMobile(shopDTO.getMobile());
        shopDTO.setShopStatus(0);
        shopDTO.setId(UUIDGenerator.generate());

        //TODO 记录推广员id
        //获取推广员的信息
        Member member = memberService.getById(JwtUtil.getUserIdByToken());
        PromotionInformation ent=new PromotionInformation();
        //推广员分成类型
        ent.setType(member.getPromotionType());
        //推广员分成比例
        ent.setProportion(member.getPromotionNum());
        ent.setAddress(shopDTO.getAddressDetail());
        ent.setShopId(shopDTO.getId());
        ent.setPromotersId(JwtUtil.getUserIdByToken());
        ent.setCreateTime(new Date());
        ent.setShopName(shopDTO.getShopName()).setType(1);
        if (sqlSeller!=null){
            if (sqlSeller.getIsDelete()==1||sqlSeller.getState()==1){
                return Result.error("该商户状态异常，无法添加该商户");
            }
        }
        else {
            seller.setId(UUIDGenerator.generate());
            seller.setType(0);
            seller.setUsername(shopDTO.getMobile());
            seller.setNickName("用户"+ RandomUtil.randomString(8));
            seller.setMobile(shopDTO.getMobile());
            sellerService.save(seller);
        }

        Shop shop= ShopConvert.INSTANCE.convert7(shopDTO);

        shopService.save(shop);
        sellerService.addSellerShopRelationShip(seller.getId(),shop.getId());
        promotionInformationService.save(ent);

        return Result.ok("创建成功");
    }

    @GetMapping("/app/getPromotShopList")
    public Result getShopList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){
        PromotionInformation promotionInformation=new PromotionInformation();
        promotionInformation.setPromotersId(JwtUtil.getUserIdByToken());
        Page<PromotionInformation> page=new Page<>();
        page.setSize(pageSize).setCurrent(pageNo);
        QueryWrapper<PromotionInformation> queryWrapper=new QueryWrapper();
        queryWrapper.setEntity(promotionInformation);
        IPage<PromotionInformation> results=promotionInformationService.page(page,queryWrapper);
        return Result.ok(results);


    }

}